1. rvest

rvest 是一個爬蟲的套件,搭配下載 xml2 套件使用。 因為像是新聞或即時動態的網頁更新相當快速,所以利用爬蟲的方式抓取網頁上想要的資訊,會相當省時省力。

library(rvest)
library(xml2)
library(dplyr)



1.1. HTML

在介紹rvest套件前先介紹一下網頁也就是我們常看到的以 https://… 開頭的網頁格式,而目前網路上大多的形式都是以 HTML 的格式呈現的,我們要抓取網頁裡要的東西,通常需要知道原始碼裡的名字

以下是一個簡單的網頁原始碼模樣:

<html>
  <head>
    <title>網頁標題</title>
  </head>
  <body>
    <div class="container">
      <p>網頁內容</p>
      <p>
        <ul>
          <li>foo</li>
          <li>bar</li>
        </ul>
      </p>
    </div>
  </body>
</html>



1.2. SelectorGadget

使用 CSS 選擇器的方式,到 google chorm 下載 SelectorGadget 這個免費的軟體,可以方便篩選在爬蟲時所需要的CSS選擇器。



1.3. rvest code

開始介紹這個套件會使用到的函數

  • read_html ( “網址” ):讀取網頁
  • html_nodes ( 讀取後的東西 , “CSS” ):給 CSS 選擇器
  • html_text ( nodes選擇完的東西 ):轉為文字
  • html_attr ( “herf” ):擷取網址

以下為擷取自由時報 Liberty Times Net 的新聞標題 :

url_news <- "http://news.ltn.com.tw/list/BreakingNews"
read_news <- read_html(url_news)  
nodes_news <- html_nodes(read_news, ".picword") 
text_news <- html_text(nodes_news) %>% as.data.frame()
news_location <- html_attr(nodes_news , "href") %>% as.data.frame()
head(text_news)
##                                             .
## 1             高市中午氣溫逼近30度 空品仍不佳
## 2      挑戰9800點大關不成 台股收盤小漲14.85點
## 3 台電員工被爆假藉標案公器私用 台電:確有瑕疵
## 4               聯合拍賣中古賓士車 只要‧‧‧
## 5             台股收盤上漲14.85點 報9778.78點
## 6        重拾失落der勇氣 許瑋甯獨往異地剉咧等
head(news_location)
##                                                           .
## 1     http://news.ltn.com.tw/news/life/breakingnews/1983030
## 2 http://news.ltn.com.tw/news/business/breakingnews/1983032
## 3 http://news.ltn.com.tw/news/business/breakingnews/1983029
## 4  http://news.ltn.com.tw/news/society/breakingnews/1983020
## 5 http://news.ltn.com.tw/news/business/breakingnews/1983012
## 6           http://ent.ltn.com.tw/news/breakingnews/1982718

另一種情況

以下直接利用 dplyr 的指令爬自由時報體育新聞Sport 的標題,注意到不一樣的地方是給的 CSS 選擇器結果不同,由於網頁設計上,其實一般的情況應該都會是不同的。

url_sport <- "http://sports.ltn.com.tw/"
sport <- read_html(url_sport) %>% html_nodes(".content .list_title") %>% html_text() %>% as.data.frame() 
sport_location <- read_html(url_sport) %>% html_nodes(".content .listA.boxTitle a") %>% html_attr("href") %>% as.data.frame()

使用SelectorGadget 選區塊時按在標題上


使用SelectorGadget 選區塊時不要按在標題上,要點在旁邊,框框會比點在標題上面大,所以選出來的果不一樣


隔一天發現使用SelectorGadget 選擇器選出來的結果不同,像這種即時的網頁其實有點會隨時做更新


以下為讀取出來的結果

讀取網址的結果都會有兩個重複的結果,這在SelectorGadget 選取的時候其實就可以發現

##                                                     .
## 1                             掃除恐古症 台灣扳回一城
## 2          經典賽》高尺巨蛋不一樣了!  新增兩面大螢幕
## 3 經典賽》官網分析台灣隊戰力 大膽看好荷蘭、以色列晉級
## 4                NBA》火箭射手傳喜訊 明星周與女友訂婚
## 5          經典賽》高尺巨蛋不一樣了!  新增兩面大螢幕
## 6             WNBA》前球員控訴遭霸凌 只因她是異性戀者
##  [1] news/breakingnews/1982888 news/breakingnews/1982888
##  [3] news/breakingnews/1982917 news/breakingnews/1982917
##  [5] news/breakingnews/1982731 news/breakingnews/1982731
##  [7] news/breakingnews/1982862 news/breakingnews/1982862
##  [9] news/breakingnews/1982863 news/breakingnews/1982863
## 15 Levels: news/breakingnews/1982643 ... news/breakingnews/1982917



1.4. 抓取多頁

利用爬蟲的方式搭配迴圈,一次抓取多頁的新聞標題,同樣以自由時報的新聞網頁為範例,假設我們要一次抓取五頁的新聞標題,先看網址的特性:只差在 page= 多少,代表是第幾頁,所以就可以快速地用迴圈幫我們執行

http://news.ltn.com.tw/list/BreakingNews?page=1
http://news.ltn.com.tw/list/BreakingNews?page=2
title <- NULL
for (i in 1:5) {
  pathfile <- paste("http://news.ltn.com.tw/list/BreakingNews?page=",i,sep = "")
  mtitle <- read_html(pathfile) %>% html_nodes(".picword") %>% html_text() 
  title <- c(title,mtitle)
}
title <- as.data.frame(title)

讀取出來的結果:

##  [1] 獨家》警除網巡還要帶風向 傳遭造冊列管                
##  [2] MLB》美媒評2017年十大爛約 1名亞洲球員上榜            
##  [3] 幫助失智老人回家,台灣大哥大拍電影展示 NFC 協尋手環!
##  [4] 高市中午氣溫逼近30度 空品仍不佳                      
##  [5] 台電員工被爆假藉標案公器私用 台電:確有瑕疵          
##  [6] 聯合拍賣中古賓士車 只要‧‧‧                        
##  [7] 台股收盤上漲14.85點 報9778.78點                      
##  [8] 重拾失落der勇氣 許瑋甯獨往異地剉咧等                 
##  [9] W命案當天險再死1女... 這名小模被檢方找到了!         
## [10] 台南玉井銅像深夜被拆 民批像作賊                      
## [11] 新北地政局副局長自殺 同仁震驚                        
## [12] 人工電子耳助聽力 慈母開心再聽到兒子笑聲              
## [13] 空污管制標準公聽會 環團、香燭金紙業者都不滿!        
## [14] 新北地政局副局長涉賄自殺 檢方澄清:僅搜索未約談      
## [15] 馬公景福祠開放乞求發財金  擲筊決定金額               
## [16] 兩岸關係雖降到冰點 中國棒球隊仍到高雄移訓            
## [17] NBA》火箭射手傳喜訊 明星周與女友訂婚                 
## [18] 被搜索後自殺身亡 王聖文遺書「我沒有拿他們的錢」      
## [19] 多家國道客運業者3/1起調漲票價                        
## [20] 山寨車與本尊保時捷 Macan,用這招相見歡?             
## [21] 孩子生活習慣太糟糕 母訂超狂生活公約反制              
## [22] 美國人最喜歡國家 加拿大第1 台灣排進前10              
## [23] 花蓮利英工礦改地下開採 環團籲重做環評                
## [24] 涉轉讓禁藥致死等罪 「土豪哥」等5人求刑共逾55年       
## [25] 警E衛?網路發言遭造冊列管 網友:東廠三重分部?      
## [26] 吳敦義要選下屆總統 郝龍斌:別將黨主席選舉當跳板      
## [27] 蔣萬安譏李逸洋「雙重人格」  李回嗆「人格不能被扭曲」 
## [28] 響應「國艦國造」 蘇海開辦全國首創的海事工程班        
## [29] 房屋隔音差 繼父姦女怎無人知? 一審判無罪             
## [30] 陽明山「花見野餐」 228連假首日邀民同樂               
## [31] 靠大伯拉拔、社會資助... 清寒生半工半讀想回饋         
## [32] 土豪哥被求刑12年 土豪爸律師:收到起訴書再回應        
## [33] 涉恐嚇、暴力討債等多案 古坑鄉代會主席交保            
## [34] 逾200台籍詐騙嫌犯遣送中國 國台辦回應了               
## [35] 她5歲性早熟  治療5年才延緩發育                       
## 121 Levels: 《釧兒》音樂劇巡演台南 澎恰恰扮說書人 ...

抓取不只一項:標題+時間

##  [1] 2017-02-22 13:47                               
##  [2] 高市中午氣溫逼近30度 空品仍不佳                
##  [3] 2017-02-22 13:42                               
##  [4] 挑戰9800點大關不成 台股收盤小漲14.85點         
##  [5] 2017-02-22 13:41                               
##  [6] 台電員工被爆假藉標案公器私用 台電:確有瑕疵    
##  [7] 2017-02-22 13:38                               
##  [8] 聯合拍賣中古賓士車 只要‧‧‧                  
##  [9] 2017-02-22 13:36                               
## [10] 台股收盤上漲14.85點 報9778.78點                
## [11] 2017-02-22 13:30                               
## [12] 重拾失落der勇氣 許瑋甯獨往異地剉咧等           
## [13] 2017-02-22 13:29                               
## [14] W命案當天險再死1女... 這名小模被檢方找到了!   
## [15] 2017-02-22 13:25                               
## [16] 新北地政局副局長自殺 同仁震驚                  
## [17] 2017-02-22 13:24                               
## [18] 人工電子耳助聽力 慈母開心再聽到兒子笑聲        
## [19] 2017-02-22 13:23                               
## [20] 空污管制標準公聽會 環團、香燭金紙業者都不滿!  
## [21] 2017-02-22 13:21                               
## [22] 新北地政局副局長涉賄自殺 檢方澄清:僅搜索未約談
## [23] 2017-02-22 13:20                               
## [24] 馬公景福祠開放乞求發財金  擲筊決定金額         
## [25] 2017-02-22 13:20                               
## [26] 兩岸關係雖降到冰點 中國棒球隊仍到高雄移訓      
## [27] 2017-02-22 13:18                               
## [28] NBA》火箭射手傳喜訊 明星周與女友訂婚           
## [29] 2017-02-22 13:14                               
## [30] 被搜索後自殺身亡 王聖文遺書「我沒有拿他們的錢」
## [31] 2017-02-22 13:10                               
## [32] 多家國道客運業者3/1起調漲票價                  
## [33] 2017-02-22 13:10                               
## [34] 山寨車與本尊保時捷 Macan,用這招相見歡?       
## [35] 2017-02-22 13:06                               
## [36] 孩子生活習慣太糟糕 母訂超狂生活公約反制        
## 43 Levels: 2017-02-22 13:00 2017-02-22 13:02 ... W命案當天險再死1女... 這名小模被檢方找到了!



2. lattice

R graphics:
1.  Traditional graphics
2.  Grid graphics: 
    1. Lattice: base on Trellis graphics
    2.ggplot2:inspired by “Grammar on Graphics”

lattice 系統是根據 grid為基礎所發展出來的一套繪圖系統,對於各種常見的圖形提供了比較高階的繪圖函數,跟傳統的 base 系統相較之下,lattice 主要有兩個特點:

第一是所有的繪圖結果都可以儲存在變數當中(不像 base 是直接畫在螢幕上的),也就是說在 lattice 系統之下,使用者可以對畫出來的圖形做進一步的修改,然後再重新畫出新的結果,對於一系列相類似的圖組也可以使用這樣的技巧加速繪圖的速度,另外也可以把繪圖結果儲存下來,供日後使用。 lattice 的第二個特色則是一張圖形中可以包含多個子繪圖區域,亦即使用者可以將多張子圖形直接放在同一張圖中一起比較,省去了自己手動合併多張圖形的困擾。

lattice default settings


範例資料

Package : mangoTraining 內建資料 
Data : tubeData 
1050 observations with 9 variables

Line: A factor with 10 levels, one for each London tube line. 
Month: categorical, the month of the observation. 
Scheduled: the scheduled running time.
Excess: The excess running time.
TOTAL: the total running time.
Opened: categorical, the year the line opened. Length: the line length.
Type: categorical, the type of tube line. 
Stations: the number of stations on the line.
##       Line Month Scheduled Excess TOTAL Opened Length Type Stations
## 1 Bakerloo     1     29.42   6.04 35.46   1906   23.2   DT       25
## 2 Bakerloo     2     29.42   6.54 35.96   1906   23.2   DT       25
## 3 Bakerloo     3     29.30   4.77 34.08   1906   23.2   DT       25
## 4 Bakerloo     4     29.30   5.40 34.70   1906   23.2   DT       25
## 5 Bakerloo     5     29.30   5.23 34.53   1906   23.2   DT       25
## 6 Bakerloo     6     29.30   5.03 34.33   1906   23.2   DT       25



2.1. histogram

利用變數 Excess 來畫直方圖瞭解一下資料狀態

histogram( ~ Excess, data = tubeData, col = "red",
           main = "Histogram of Excess Time",
           xlab = "Excess Journey Times (Hours)",
           nint = 25)

histogram( ~ Excess | Type, data = tubeData ,
           main = "Histogram of Excess Time",
           xlab = "Excess Journey Times (Hours)",
           nint = 25)



2.2. xyplot

xyplot(Excess ~ Month , data = tubeData, 
       type = c("p", "smooth"))

xyplot(Excess ~ Month , data = tubeData, groups = Line,
      auto.key = list(space="right"),
       main = "Excess Journey Times vs Month by Line",
       xlab = "The Month of The Observation",
       ylab = "Excess Journey Times (Hours)")

xyplot(Excess ~ Month | Line, data = tubeData, col = "blue",layout=c(5,2),
       main = "Excess Journey Times vs Month by Line",
       xlab = "The Month of The Observation",
       ylab = "Excess Journey Times (Hours)")

xyplot(Excess ~ Month , data = tubeData, groups = Line,type="l",
       auto.key = list(space="right"),
       main = "Excess Journey Times vs Month by Line",
       xlab = "The Month of The Observation",
       ylab = "Excess Journey Times (Hours)")

xyplot(Excess ~ Month | Line, data = tubeData, col = "blue",type = "l",layout=c(5,2),
       main = "Excess Journey Times vs Month by Line",
       xlab = "The Month of The Observation",
       ylab = "Excess Journey Times (Hours)")

xyplot(Excess ~ Month , data = tubeData, subset = Line =="Central",
       col = "blue",type = "l",
       main = "Excess Journey Times vs Month of Central",
       xlab = "The Month of The Observation",
       ylab = "Excess Journey Times (Hours)")

xyplot(Excess ~ Month | cut(Length, c(0, 20, 50, 100)), data = tubeData,
       col = "blue", layout = c(3, 1),
       main = "Excess Journey Times vs Month by Length (km)",
       xlab = "The Month of The Observation",
       ylab = "Excess Journey Times (Hours)")



2.3. bwplot

bwplot( ~Excess, data = tubeData)

bwplot(Line ~ Excess  , data = tubeData,
       main = "Excess Journey Times by Line",
       xlab = "Excess Journey Times (Hours)")

bwplot(~ Excess | cut(Length, c(0, 20, 50, 100)) , data = tubeData, layout = c(1, 3),
       main = "Excess Journey Times by Length (km)",
       xlab = "Excess Journey Times (Hours)")

bwplot(Type ~ Excess | cut(Length, c(0, 20, 50, 100)) , data = tubeData,layout = c(1, 3),
       main = "Excess Journey Times by Length (km) & Type",
       xlab = "Excess Journey Times (Hours)")



2.4. densityplot

densityplot(~ Excess, data = tubeData,lwd = 2, 
            main = "Density of Excess Time",
            xlab = "Excess Journey Times (Hours)") 

densityplot( ~ Excess,
             data = tubeData,
             groups = Line,
             type = "n",
             auto.key = list(space = "right"), lwd = 1,
             main = "Density of Excess Time Separated Plots by Lines", 
             xlab = "Excess Journey Times (Hours)")



2.5. qqmath

qqmath( ~ Excess, data = tubeData, main = "QQplot of Excess Time")

qqmath( ~ Excess, data = tubeData, groups = Type,
        auto.key = list("top", columns=2),
        main = "QQplot of Excess Time by Type")



2.6. dotplot

dotplot(Line ~ Length , data = tubeData)

dotplot(reorder(Line, Length) ~ Length , data = tubeData)



2.7. cloud

cloud(Excess ~  Length * Month, data = tubeData)



2.8. splom

splom(~tubeData[2:5])

splom(~tubeData[2:5], groups = Type, data = tubeData,
      auto.key = list( "top", columns=2))



2.9. barchart

barchart( ~ Line, data = tubeData, groups = Type, auto.key = TRUE)


用另一組皆為類別型的資料來看 barchart的使用

Package : MASS 內建資料 
Data : housing 出租房屋滿意度調查.
72 rows, 5 variables.

Sat: 屋主對目前房屋的滿意度: High, Medium, Low.
Infl: 屋主對資產管理的認知: High, Medium, Low.
Type: 房屋型式: Tower, Atrium, Apartment, Terrace. 
Cont: 經由其他房客提供可以接觸房客的機會: Low, High 
Freq: 每一分類的人數.
##      Sat   Infl  Type Cont Freq
## 1    Low    Low Tower  Low   21
## 2 Medium    Low Tower  Low   21
## 3   High    Low Tower  Low   28
## 4    Low Medium Tower  Low   34
## 5 Medium Medium Tower  Low   22
## 6   High Medium Tower  Low   36
barchart(Freq ~ Infl | Type + Cont, groups = Sat,
         data = housing, stack = TRUE)

barchart(xtabs(Freq ~ Sat + Infl + Type + Cont, data = housing))

dotplot(Sat+Infl ~ Freq | Type+Cont, data = housing , auto.key = TRUE)



2.10. levelplot

如果資料是格狀的地理資訊,可以直接利用 levelplot 函數繪圖,而 wireframe 函數可以繪製 3D圖

Data : volcano
紐西蘭的 Auckland 附近約有 50 座火山,Maunga Whau 是其中的一座,volcano 是一組 87 × 61 矩陣,紀錄 Maunga Whau 10m × 10m 格狀的地理資訊.
levelplot(volcano)

wireframe(volcano, drape = TRUE)